import React, { PropTypes, Component } from 'react'
import fetch from 'isomorphic-fetch'
import { Link } from 'react-router'

import { myAjax, ROOTURL } from './../publicAPI/publicAPI'
import Table from './Table'
import NavLink from './NavLink'



class WalletM extends Component {

    constructor(props, context) {
        super(props, context)
        console.log("初始化")
        this.state = {
            
            account:[],
           
            
        };// 初始化状态
        this.start=0;
        this.page=1;
    }

    componentWillMount() {
         this.findAccount("","");
       
    }

    componentDidMount() {
        console.log("安装成功")
    }
    findAccount(dname,phone){
        console.log(dname);
        console.log(phone);
        let _this=this
        let params={
              "where":{},
            
              "order":
                [           // ORDER BY  
                    ["id", "DESC"],  
         
                ],
                "limit":10
             
            
         
        }
        if(dname!=""){
        params={
           "where":
            {"dname":
                [
                    ["eq",dname]
                ],
             
            },
            "order":
            [           // ORDER BY  
                    ["id", "DESC"],    
         
            ],
            "limit":10
             
         }
        }
        else if(phone!=""){
            params={
            "where":
                {"customer":{
                    "phone":[
                        ["eq",phone]
                    ],
                  }
                },
            "order":
                [           // ORDER BY  
                    ["id", "DESC"],    // id ASC,
         
                ],
                "limit":10
             
            }
        }

        else if(phone!=""&&dname!=""){
            params={
             "where":{
                "customer":{
                    "phone":[
                        ["eq",phone]
                    ],
                },
                "dname":
                [
                    ["eq",dname]
                ],
                
              },
               "order":
                [           // ORDER BY  
                    ["id", "DESC"],    // id ASC,
         
                ],
                "limit":10
            }
        }    
        this.HandleInfoById(params);



      
        
            
    }
    
    HandleInfoById(params){//获取钱包用户普通信息

        let _this=this;
        fetch(ROOTURL+'/wallet/account/search.api',{
                method: 'post',
                headers: {
                    "Content-type": "application/json; charset=UTF-8"
                },
        
                body:JSON.stringify(params)
        }).then(response=>{return response.json()})
        .then(data=>{
            _this.handlePhoneById(data);

         


        })






    }
    

    handlePhoneById(AccountInfo){//通过id获取用户手机号,AccountInfo为用户的普通信息数组
           let IdArray=[];
           let phoneArray=[];
           AccountInfo.map(function(elem, index) {
                 IdArray.push(elem.id);
           });
        
         //console.log(AccountInfo);
           let params={
              "where":{
                "id":
                [
                    ["in",IdArray]
                ],
                
              },
               "order":
                [           // ORDER BY  
                    ["id", "DESC"],    // id ASC,
         
                ],
                "limit":10




           }
           fetch(ROOTURL+'/customer/profile/search.api',{
                method: 'post',
                headers: {
                    "Content-type": "application/json; charset=UTF-8"
                },
        
                body:JSON.stringify(params)
        }).then(response=>{return response.json()})
        .then(
            data=>{ data.map(function(elem, index) {
                     AccountInfo[index].phone=elem.phone;
                     //console.log(AccountInfo[index]);
                    });
                   
                    this.setState({
                        account:AccountInfo
                    })
                    
                  }
            )

      


    }


    handleSearchClick(e) {
            let dname=this.refs.dname.value;
            let phone=this.refs.phone.value;
            this.findAccount(dname,phone);
    }
        

   
    handlePageClick(e) { //1为下一页，2为上一页
        let _buttonValue = e.target.value;
        let next=document.getElementsByClassName("next")[0];
        let prev=document.getElementsByClassName("prev")[0];
        let _this=this;
      
       
        if (_buttonValue == 1) {
          
          this.start=this.start+9;
          this.page++;
          prev.style.display="block";

        } else {
          this.start=this.start-9;
          this.page--;
          next.style.display="block";
        }
        console.log(this.page);
        let params={
             "order":
            [           // ORDER BY  
                    ["id", "DESC"],    // id ASC,
         
            ],
            "start":this.start,//
            "limit":10

        }
        if(this.page==1){
       
            prev.style.display="none";
        }






        if(this.start>=0){//如果当前页页码是负数则不请求数据
          
           fetch(ROOTURL+'/wallet/account/search.api',{
                method: 'post',
                headers: {
                    "Content-type": "application/json; charset=UTF-8"
                },
        
                body:JSON.stringify(params)
            }).then(response=>{return response.json()})
             .then(data=>{
                     console.log("legth:"+data.length);
                     if(data.length<10)
                    next.style.display="none";
                    this.handlePhoneById(data);
             })
          
          
          
           

       
         //console.log("StatePage:"+_this.state.page);
          //console.log("StatetobeEnd:"+_this.state.toBeEnd);
        }
        
        

    }




    tHead() {
        var data = [
            {name: "id"},
            {name: "微信名"},
            {name: "电话"},
            {name: "余额"},
            {name: "详细使用记录"},
        ];
        const _headArr = [];
        const _width = {
            "0":"20%",
            "1":"20%",
            "2":"20%",
            "3":"20%",
            "4":"20%"
        };
       
        _headArr.push(data.map((item, index) => <th style={{width: _width[index]}} role="1"
                                                    key={index}>{item.name}</th>));
        return _headArr;
    }

    tBody() {
        let _data = this.state.account;

        return _data.map((item) => <tr key = {item.id} >

                     < td > { item.id } < /td> 
                     < td > { item.dname } < /td > 
                     < td > { item.phone } < /td> 
                     < td > { item.balance } < /td >
                     <td>
                        <span><NavLink to={`/WalletM/${item.id}`} className="rbtn green">查看</NavLink></span>
                     </td>
        </tr>)
    }

    render() {
        
        return (
            	<div className="right-wapper" style={{height: this.state.rHeight}}>
	    		<div className="rt-wrap rt-wrap-header">
	    			<div className="input-div pr">
		    			<label>微信号：</label>
		    			<input type="text" placeholder="请输入要查找的微信号" className="default-text"
		    				ref="dname"/>
		    		</div>
		    		<div className="input-div">
		    			<label>电话号码：</label>
		    			<input type="text" placeholder="请输入要查找的电话号码" className="default-text"
		    				ref="phone" />
		    		</div>
		    		<div className="input-div">
		    			<button className="search-btn" onClick={(e) => this.handleSearchClick(e)}>查找</button>
		    		</div>
		    		
	    		</div>
		    		
	    		<div className="rt-wrap">
	    			<h3 className="catagory">
	    				<span className="cata-title">客户列表</span>
	    				<button className="next" value="1" onClick={(e) => this.handlePageClick(e)}></button>
	    				<button style={{display:'none'}} className="prev" value="2" onClick={(e) => this.handlePageClick(e)}></button>
	    			</h3>
	    			<Table tHead={this.tHead.bind(this)()} tBody={this.tBody.bind(this)()}/>
	    		</div>
	    		
	    	</div>

        )
    }
}

export default WalletM
